package com.gc.server.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.gc.server.dao.ApplyItemDao;
import com.gc.server.dao.GoodsDao;
import com.gc.server.dao.UserDao;
import com.gc.server.entity.ApplyItemEntity;
import com.gc.server.entity.GoodsEntity;
import com.gc.server.entity.UserEntity;
import com.gc.server.enums.GoodsApplyStatusEnum;
import com.gc.server.vo.GoodsApplyVo;
import com.gc.server.vo.down.ApplyGoodsItemDown;
import com.gc.server.vo.down.GoodsApplyDown;
import com.yf.response.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.gc.server.dao.GoodsApplyDao;
import com.gc.server.entity.GoodsApplyEntity;
import com.gc.server.service.GoodsApplyService;
import com.yf.service.impl.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;

/**
 * 物料申请Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Tue Mar 10 11:17:45 CST 2020
 */
@Service
public class GoodsApplyServiceImpl extends BaseServiceImpl<GoodsApplyEntity> implements GoodsApplyService {

    private GoodsApplyDao goodsApplyDao;

    @Autowired
    private ApplyItemDao applyItemDao;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    public void setDao(GoodsApplyDao goodsApplyDao) {
        this.goodsApplyDao = goodsApplyDao;
        super.setBaseDao(goodsApplyDao);
    }


    @Override
    public List<GoodsApplyVo> queryListVo(GoodsApplyVo goodsApplyVo) {
        return goodsApplyDao.queryListVo(goodsApplyVo);
    }

    @Override
    public GoodsApplyVo getVo(Long id) {
        return goodsApplyDao.getVo(id);
    }


    /**
     * 内部方法
     **/

    private String createNO(Long userId) {
        return System.currentTimeMillis() + "" + Math.round(Math.random() * 100) + "" + userId;
    }


    /**
     * 外部方法实现
     **/

    @Override
    @Transactional(rollbackFor = Exception.class)
    public GoodsApplyEntity apply(Long userId, Long[] ids, Integer[] nums, String remark, String address, String unit) {
        String orderNo = createNO(userId);
        GoodsApplyEntity goodsApplyEntity = new GoodsApplyEntity(userId, remark, orderNo, GoodsApplyStatusEnum.WAIT.getIndex(), new Date(), address, unit);
        goodsApplyDao.save(goodsApplyEntity);
        Integer sumNum = 0;
        BigDecimal price = BigDecimal.ZERO;
        for (int i = 0; i < ids.length; i++) {
            GoodsEntity goodsEntity = goodsDao.get(ids[i]);
            ApplyItemEntity applyItemEntity = new ApplyItemEntity(ids[i], goodsEntity.getName(), goodsEntity.getPrice(), nums[i]);
            applyItemEntity.setApplyId(goodsApplyEntity.getId());
            applyItemDao.save(applyItemEntity);
            sumNum += nums[i];
            price = price.add(goodsEntity.getPrice().multiply(new BigDecimal(applyItemEntity.getNumber())));
        }
        goodsApplyEntity.setPrice(price);
        goodsApplyEntity.setAmount(sumNum);
        goodsApplyDao.update(goodsApplyEntity);
        return goodsApplyEntity;
    }

    @Override
    public List<GoodsApplyVo> findByUserId(Long userId, Date startDate, Date endDate) {
        return goodsApplyDao.findByUserId(userId, startDate, endDate);
    }

    @Override
    public BigDecimal sumAmount(Date date, Long userId) {
        return goodsApplyDao.sumAmount(date, userId);
    }

    @Override
    public BigDecimal sumAmountByPid(Date date, Long userId) {
        return goodsApplyDao.sumAmountByPid(date, userId);
    }

    @Override
    public List<GoodsApplyVo> findByPid(Long userId, Date startDate, Date endDate) {
        return goodsApplyDao.findByPid(userId, startDate, endDate);
    }

    @Override
    public Integer sumCheck(Long userId) {
        return goodsApplyDao.sumCheck(userId);
    }

    @Override
    public GoodsApplyEntity check(Long userId, Long id, Integer status, String remark) {
        GoodsApplyEntity goodsApplyEntity = get(id);
        goodsApplyEntity.setStatus(status);
        goodsApplyEntity.setRemark(remark);
        UserEntity userEntity = userDao.get(goodsApplyEntity.getUserId());
        if (status != GoodsApplyStatusEnum.RECEIVE.getIndex() && !userId.equals(userEntity.getPid())) {
            throw new RRException("没有权限!");
        }
        goodsApplyEntity.setAdminId(userId);
        UserEntity p = userDao.get(userId);
        goodsApplyEntity.setAdminName(p.getName());
        update(goodsApplyEntity);
        return goodsApplyEntity;
    }

    @Override
    public void downLoad(HttpServletResponse response, List<GoodsApplyVo> list) {
        try {
            List<GoodsApplyDown> datas = list.stream().map(item -> new GoodsApplyDown(item)).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //记录
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
            //明细
            List<ApplyGoodsItemDown> itemDowns = sumGoodsItem(datas);
            WriteSheet writeSheet = EasyExcel.writerSheet(0,"汇总").head(ApplyGoodsItemDown.class).build();
            excelWriter.write(itemDowns, writeSheet);
            //记录
            writeSheet = EasyExcel.writerSheet(1,"记录").head(GoodsApplyDown.class).build();
            excelWriter.write(datas, writeSheet);
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private List<ApplyGoodsItemDown> sumGoodsItem(List<GoodsApplyDown> datas) {
        Map<String, ApplyGoodsItemDown> sum = new HashMap();
        for (GoodsApplyDown apply : datas) {
            StringBuilder sb = new StringBuilder();
            List<ApplyItemEntity> itemEntities = itemDao.findByApplyId(apply.getId());
            for (ApplyItemEntity itemEntity : itemEntities) {
                sb.append(itemEntity.getGoodsName()).append("X").append(itemEntity.getNumber()).append(" ");
                ApplyGoodsItemDown itemDown = new ApplyGoodsItemDown(itemEntity.getGoodsName(), itemEntity.getPrice(), 0, BigDecimal.ZERO);
                if (sum.containsKey(itemEntity.getGoodsName())) {
                    itemDown = sum.get(itemEntity.getGoodsName());
                    itemDown.addQuantity(itemEntity.getNumber());
                    if(itemEntity.getPrice().compareTo(BigDecimal.ZERO)==0){
                        GoodsEntity goodsEntity = goodsDao.get(itemEntity.getGoodsId());
                        if(goodsEntity!=null){
                            itemDown.setPrice(goodsEntity.getPrice());
                        }
                    }
                }
                apply.setGoodsName(sb.toString());
                sum.put(itemEntity.getGoodsName(), itemDown);
            }
        }
        return sum.values().stream().collect(Collectors.toList());
    }


    @Autowired
    private ApplyItemDao itemDao;


    @Autowired
    private UserDao userDao;
}


